package com.sfang.common.util.verifyCode;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sfang.common.base.entity.RestInfo;
import com.sfang.common.util.http.HttpClientUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CaptchaUtil {

    private static final String url="https://webapi.sms.mob.com/sms/verify";

    private static final String sendUrl = "https://webapi.sms.mob.com/sms/sendmsg";

    private static final String mobAppKey = "195bd0b311cb2";

    private static Logger LOGGER = LoggerFactory.getLogger(CaptchaUtil.class);


    public static RestInfo mobSendPhonCode(String phone, String areacode, String message){
        RestInfo restInfo = HttpClientUtils.sendPostJSON(sendUrl, String.format("appkey=%s&zone=%s&phone=%s", mobAppKey, areacode, phone), null);
        return restInfo;
    }


    public static String validatePhoneCode(String appKey,String phone, String phoneAreaCode,String phoneCaptcha){

        Map<String,String> map=new HashMap<String,String>();
        map.put("appkey",appKey);
        map.put("phone",phone);
        map.put("zone",phoneAreaCode);
        map.put("code",phoneCaptcha);

        String body = "";

        try {
            //创建httpclient对象
            CloseableHttpClient client = HttpClients.createDefault();
            //创建post方式请求对象
            HttpPost httpPost = new HttpPost(url);

            //装填参数
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            if(map!=null){
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
            }
            //设置参数到请求对象中
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));

            System.out.println("请求地址："+url);
            System.out.println("请求参数："+nvps.toString());

            //设置header信息
            //指定报文头【Content-type】、【User-Agent】
            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
            httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

            //执行请求操作，并拿到结果（同步阻塞）
            CloseableHttpResponse response = client.execute(httpPost);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity, "UTF-8").split(":")[1].replace("}","");
            }

            EntityUtils.consume(entity);
            //释放链接
            response.close();
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
        }
        return body;
    }

    public static void main(String[] args){
        RestInfo restInfo = CaptchaUtil.mobSendPhonCode("13879331663", "86", null);
        String result = (String)restInfo.getData();
        JSONObject jsonObject = JSON.parseObject(result);
        Integer status = jsonObject.getInteger("status");
        System.out.println(CaptchaUtil.convertMobMessage(status));
    }

    public static String convertMobMessage(int status){
        String message = "";
        switch (status) {
            case 206:
                message = "模板不存在/未审核/非验证码模板";
                break;
            case 222:
                message = "短信内容超过70个字符";
                break;
            case 405:
                message = "请求参数中的appkey为空";
                break;
            case 406:
                message = "非法的appkey";
                break;
            case 456:
                message = "请求参数中的手机号码或者国家代码为空";
                break;
            case 457:
                message = "亲，看起来不像手机号呢!";
                break;
            case 458:
                message = "AppKey或手机号码在黑名单中";
                break;
            case 460:
                message = "未开启发送短信功能，请联系我们";
                break;
            case 462:
                message = "应用下同一手机号1分钟内发送短信的次数超过2次";
                break;
            case 463:
                message = "手机号码超出当天发送短信的限额";
                break;
            case 467:
                message = "请求校验验证码频繁（5分钟校验超过3次）";
                break;
            case 468:
                message = "验证码错误";
                break;
            case 469:
                message = "没有打开发送Http-api的开关";
                break;
            case 470:
                message = "账户短信余额不足";
                break;
            case 471:
                message = "请求ip和绑定ip不符";
                break;
            case 475:
                message = "应用信息不存在，检查appKey是否低于2.0版本";
                break;
            case 477:
                message = "获取验证码超过限制次数";
                break;
            case 488:
                message = "当前手机号码在当前应用下12小时内最多可发送文本验证码5条";
                break;
        }
        return message;
    }
}
